using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using XNgine.CameraManagement;
using XNgine.ObjectManagement.Infos;
using XNgine.Services;

namespace XNgine.ObjectManagement.RenderModels
{
    public class ModelRenderer: IRenderModel
    {
        public bool loaded;

        public string ModelPath { get; set; }
        public Model Model { get; set; }

        public ModelRenderer(string modelPath)
        {
            ModelPath = modelPath;
        }

        public void Render(DimensionInfo dimensionInfo)
        {
            if(!loaded)
            {
                LoadContent();
            }
            if (!loaded) return;
            
            ICamera camera = XEngine.Instance.GetService<ICameraManagement>().ActiveCamera;

            Matrix[] transforms = new Matrix[Model.Bones.Count];
            Model.CopyAbsoluteBoneTransformsTo(transforms);

            // Set some renderstates so the model will draw properly
            XEngine.Instance.GraphicsDevice.RenderState.AlphaBlendEnable = true;
            XEngine.Instance.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
            XEngine.Instance.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
            XEngine.Instance.GraphicsDevice.RenderState.DepthBufferEnable = true;

            // Loop through meshes and effects and set them up to draw
            foreach (ModelMesh mesh in Model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    // Set effect parameters
                    effect.Parameters["World"].SetValue(transforms[mesh.ParentBone.Index] * dimensionInfo.World);
                    effect.Parameters["View"].SetValue(camera.View);
                    effect.Parameters["Projection"].SetValue(camera.Projection);

                    // Enable lighting
                    effect.EnableDefaultLighting();
                }

                // Draw the mesh
                mesh.Draw();
            }
        }

        public void LoadContent()
        {
            Model = XEngine.Instance.Content.Load<Model>(ModelPath);
            loaded = true;
        }

        public void UnloadContent(){}
    }
}